<template>
  <a-spin :spinning="spinning">
  <base-breadcrumb>
    <a-card :bordered="false">
      <title-name v-if="isEdit == 0" title="新增双优化立项申请表" />
      <title-name v-if="isEdit == 1" title="编辑双优化立项申请表" />
      <a-form-model ref="form1" layout="horizontal" :model="form" :rules="rules">
        <!--<a-form-model layout="horizontal" ref="form1" :model="form" :rules="rules" hideRequiredMark>-->
          <a-row :gutter="24">
            <a-col :md="16" :sm="16">
              <a-form-model-item label="所属单位" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="projectId">
                <org-tree-select is-need-auth :is-auto-select-first="isEdit==0" check-strictly v-model="form.projectId" @handleChange="handleChange" @select="selectOrg" @getProjectInfo="getProjectInfo" />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="双优化立项编号" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="optimizationNum">
                <BaseInput v-model="form.optimizationNum" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="项目业态" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="_projectFormatName">
                <BaseInput v-model="form._projectFormatName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="项目设计管理类别" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="_designName">
                <BaseInput v-model="form._designName" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="双优化立项名称" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="optimizationName">
                <BaseInput v-model="form.optimizationName" :max-length="30" placeholder="输入/选择双优化立项名称" :disabled="true" @change="getOptimitionDel()" />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8" style="line-height: 40px"> <a-button type="primary" @click="changeData" :loading="loading.isSelect"> 选择 </a-button>（从双优化立项计划表中选择） </a-col>

            <a-col :md="8" :sm="8">
              <a-form-model-item label="分类" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="typeId">
                <a-select disabled v-model="form.typeId" placeholder="" @change="getCategrys">
                  <a-select-option :value="111">
                    设计优化
                  </a-select-option>
                  <a-select-option :value="222">
                    施工组织设计（方案）优化
                  </a-select-option>
                  <!--<a-select-option v-for="item in optimizationTypes" :value="item.id">{{ item.name }}</a-select-option>-->
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="详细分类" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="classification">
                <a-select v-model="form.classification" placeholder="" disabled>
                  <a-select-option v-for="item in detailedClassification" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="设计阶段" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="_designStageName">
                <BaseInput v-model="form._designStageName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="优化类别" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="_optimizeStageName">
              <!--  <BaseInput v-model="form._optimizeStageName" disabled />-->
                <a-select
                    v-model="form.optimizeStageId"
                    :placeholder="form._optimizeStageName"
                    :disabled="view"
                    :loading="loading.category"
                >
                  <a-select-option
                      v-for="item in optimizationCategoryList"
                      :key="item.id"
                      :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="工程类别" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="projectType">
                <BaseInput v-model="form.projectType" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="分部" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="part">
                <BaseInput v-model="form.part" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="创新" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="isNew">
                <a-radio-group v-model="form.isNew" disabled>
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <!--:isLazyLoad="true"-->
              <!--:useSingle='true'-->
              <a-form-model-item label="提出人" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="proposerIds">
                <!-- <OrgStaffAsync ref="orgStaffAsync" v-model="form.proposerIds" placeholder="请选择/多选" :is-lazy-load="false" :query-api="getDesignEmployee" :selected-value.sync="form.proposerIds" /> -->
                <SelectPersonByProject
                  ref="tcrRef"
                  :row="forSelectPersonByProjectComp"
                  v-model="form.proposerIds"
                  placeholder="请输入姓名进行查询/多选"
                  show-search
                  mode="multiple"
                  orgId="53085e2c9f1f4685801ef31994f57c49"
                ></SelectPersonByProject>
                <!-- <PagingSelection /> -->
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="拟实施人" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="implementerIds">
                <!-- <OrgStaffAsync ref="orgStaffAsync1" v-model="form.implementerIds" placeholder="请选择/多选" :is-lazy-load="false" :query-api="getDesignEmployee" :selected-value.sync="form.implementerIds" /> -->
                <SelectPersonByProject
                  ref="nssrRef"
                  :row="forSelectPersonByProjectComp"
                  v-model="form.implementerIds"
                  placeholder="请输入姓名进行查询/多选"
                  show-search
                  mode="multiple"
                  orgId="53085e2c9f1f4685801ef31994f57c49"
                ></SelectPersonByProject>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="立项效益(万)" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="forecastBenefit">
                <!-- <BaseInput
                  v-model="form.forecastBenefit"
                  placeholder="请输入"
                /> -->
                <BaseInputNumber v-model="form.forecastBenefit" :precision="2" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="计划实施时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="startTime">
                <a-date-picker v-model="form.startTime" style="width: 100%" format="YYYY-MM-DD" @change="getContractStartDate" />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="计划结束时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="endTime">
                <a-date-picker v-model="form.endTime" style="width: 100%" format="YYYY-MM-DD" @change="getContractEndDate" />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="专业类别" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="majorCategory">
                <a-select v-model="form.majorCategory">
                  <a-select-option :value="0">
                    建筑
                  </a-select-option>
                  <a-select-option :value="1">
                    机电
                  </a-select-option>
                  <a-select-option :value="2">
                    结构
                  </a-select-option>
                  <a-select-option :value="3">
                    市政景观
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="创建人" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="form.creater" placeholder="" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="创建时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="form.createdTime" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-form-model-item label="内容概述" :label-col="{ lg: { span: 2 }, sm: { span: 2 } }" :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }">
                <editor v-model="form.contentDels" :is-clear="true" :max-length="3000" @change="editorContent" />
                <!--                <BaseTextarea-->
                <!--                        v-model="form.contentDels"-->
                <!--                        :auto-size="{ minRows: 20, maxRows: 25 }"-->
                <!--                        :max-length="3000"-->
                <!--                        placeholder="请输入"-->
                <!--                />-->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-form-model-item label="预计优化效益测算依据" :label-col="{ lg: { span: 2 }, sm: { span: 2 } }" :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }" prop="calculationBasis">
                <BaseTextarea v-model="form.calculationBasis" :auto-size="{ minRows: 20, maxRows: 25 }" :max-length="3000" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
          </a-row>
      </a-form-model>
    </a-card>

    <a-card>
      <title-name title="上传相关附件" />
      <UploadTableNew btnText="上传附件" ref="uploadTable" :init-file-list="file.dataAssement" :business-code="file.businessCode">
        <span slot="head" style="margin-left: 5px">请上传相关立项证明文件，例如：设计文件、设计变更单等 </span>
      </UploadTableNew>
    </a-card>

    <div class="page-btn-right-top">
      <a-button type="primary" :loading="loading.isDraft" @click="saveDraft">
        保存草稿
      </a-button>
      <a-button type="primary" class="ml12" :loading="loading.isSubimt" @click="submit">
        提交
      </a-button>
      <a-button type="primary" class="ml12" @click="goBack">
        关闭
      </a-button>
    </div>
    <a-modal v-model="visible" width="1200px" :title="title">
      <template slot="footer">
        <a-button key="back" @click="handleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="handleOk">
          确定选择
        </a-button>
      </template>

      <searchData :search-data="searchOptions" @search="handleSearch" />

      <a-table ref="table" :pagination="false" bordered :columns="columns" :data-source="dataSource" :row-selection="rowSelection">
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="project" slot-scope="text, record">{{ record.doubleOptimizationBasicVO.project }} </span>
        <span slot="branchOffice" slot-scope="text, record">{{ record.doubleOptimizationBasicVO.branchOffice }} </span>
        <span slot="isProject" slot-scope="text, record">
          <span v-if="record.isProject == true">已立项</span>
          <span v-if="record.isProject == false">未立项</span>
        </span>
      </a-table>

      <pagination v-model="objFrom.pageNo" :total="totalSize" :page-size.sync="objFrom.pageSize" @change="handlePageChange" @showSizeChange="showSizeChange" />
    </a-modal>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
  </a-spin>
</template>

<script>
import Vue from 'vue'
import { addOptimization, editOptimization, getOptimizationDetails, deleteOptimizationFile, updateBasicStatusOptimization } from '@/api/project/optimization'
import { getUserBranch, getUserProject, getProjectsDel } from '@/api/project/projects'
import { getTechnicalTypes, getProjectIdFromOrg } from '@/api/commons'
import OrgStaffAsync from '@/components/TreeSelectOrganization/orgStaffAsync.vue'
import { planListDetails } from '@/api/technical/optimizationPlan'
import { uploadFile, deleteUploadFile } from '@/api'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/SelectProjects/SelectProject' // 项目
import editor from '@/components/Editor/editor'
import ARow from 'ant-design-vue/es/grid/Row'
import SelectPersonByProject from '@/views/technical/optimizationPlan/addToReporting/selectPerson.vue' // 人员选择
import PagingSelection from './components/PagingSelection.vue' // 人员选择
import { list } from '@/api/technical/config' //双优化类别

const searchOptions = [
  {
    name: '双优化立项计划项名称',
    value: 'name',
    type: 'input'
  },
  {
    name: '双优化类型',
    value: 'categoryName',
    type: 'select',
    data: [
      { label: '设计优化', value: '设计优化' },
      { label: '施工组织设计（方案）优化', value: '施工组织设计（方案）优化' }
    ]
  },
  {
    name: '分公司',
    valueKey: 'branchOffice',
    type: SelectSubCompany
  },
  {
    name: '项目',
    keyValue: 'branchOffice',
    valueKey: 'project',
    type: SelectProject
  },
  {
    name: '立项情况',
    value: 'isProject',
    type: 'select',
    data: [
      {
        label: '全部',
        value: ''
      },
      {
        label: '未立项',
        value: 'false'
      },
      {
        label: '已立项',
        value: 'true'
      }
    ]
  }
]

const columns = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '双优化立项计划项名称',
    dataIndex: 'name',
    width: '20%'
  },
  {
    title: '类型',
    dataIndex: 'categoryName',
    width: '10%'
  },
  {
    title: '详细分类',
    dataIndex: 'detailedCategoryName',
    width: '15%'
  },
  {
    title: '项目',
    dataIndex: 'project',
    width: '20%',
    scopedSlots: { customRender: 'project' }
  },
  {
    title: '分公司',
    dataIndex: 'branchOffice',
    width: '10%',
    scopedSlots: { customRender: 'branchOffice' }
  },
  {
    title: '立项情况',
    dataIndex: 'isProject',
    width: '15%',
    scopedSlots: { customRender: 'isProject' }
  }
]

const columnAssment = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '35%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '35%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    editor,
    OrgStaffAsync,
    SelectPersonByProject,
    PagingSelection,
    SelectSubCompany,
    SelectProject
  },
  data() {
    return {
      deleteUploadFileFun: deleteUploadFile,
      columns,
      columnAssment,
      searchOptions,

      totalSize: 0,
      totalPage: 0,
      objFrom: {
        pageSize: 20,
        pageNo: 1,
        query: {
          status: 2,
          projectId: '',
          isProject: 'false'
        }
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      // 附件上传
      file: {
        dataAssement: [],
        businessCode: 'PM17'
      },
      uploadFile: {},
      deleteObj: {},
      token: '',
      fileFileds: null,
      fileIds: [],

      selectedRowKey: [],
      selectedRow: [],
      selectId: [],

      loading: {
        isDraft: false,
        isSubimt: false,
        isSelect: false,
        category: false
      },
      view: true,
      optimizationCategoryList: [], //优化类别

      spinning: false,

      // 双优化附件上传
      listUrl: '',
      deleteUrl: '/cscec-project-business/file/business/project-fileDelete',
      uploadList: '/cscec-project-business/file/business/fileUpload',

      treeCheckabel: true, // 是否多选

      data: [],
      dataSource: [],

      optimizationTypes: [], // 优化类型
      detailedClassification: [], // 详细分类

      visible: false,
      title: '选择双优化立项计划项',

      form: {
        name: '',
        creater: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        proposerIds: [],
        implementerIds: [],
        startTime: '',
        increaseBenefit: null,
        reduceBenefit: null,
        forecastBenefit: '',
        createdTime: '',
        optimizationName: '',
        classification: undefined,
        majorCategory: null, //  专业类别
        _projectFormatName: null, //  项目业态（后台不保存）
        _designName: null, //  项目设计管理类别（后台不保存）
        designStageId: null, //  设计阶段
        _designStageName: null, //  设计阶段（文本）
        optimizeStageId: null, //  优化类别
        _optimizeStageName: null, //  优化类别（文本）
        projectType: null, //  工程类别（文本）
        projectTypeId: null, //  工程类别
        part: null, //  分部（文本）
        partId: null, //  分部
        isNew: null //  创新
      },
      currentDate: '', // 当前日期

      selectedRowKeys: [],
      selectedRows: [],
      forSelectPersonByProjectComp: {}, //  用于【提出人】【拟实施人】组件
      isEdit: '',
      id: '',

      companys: [],
      projectNames: [],
      projectType: '',

      deptId: '', // 项目部id

      startDate: '', //  开始时间
      endDate: '', //    结束时间

      rules: {
        branchId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        // optimizationNum: [{ required: true, message: '双优化立项编号', trigger: 'change' }],
        optimizationName: [{ required: true, message: '请输入双优化立项名称', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择优化类型', trigger: 'change' }],
        classification: [{ required: true, message: '请选择详细分类', trigger: 'change' }],
        proposerIds: [{ type: 'array', required: true, message: '请选择提出人', trigger: 'change' }],
        implementerIds: [{ type: 'array', required: true, message: '请选择拟实施人', trigger: 'change' }],
        forecastBenefit: [{ required: true, message: '请输入立项效益', trigger: 'blur' }],
        reduceBenefit: [{ required: true, message: '请输入预测减亏效益', trigger: 'blur' }],
        increaseBenefit: [{ required: true, message: '请输入预计增加效益', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择计划实施时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择计划结束时间', trigger: 'change' }],
        majorCategory: [{ required: true, message: '请选择专业类别', trigger: 'change' }],
        contentDels: [{ required: true, message: '请输入内容概述', trigger: 'blur' }],
        calculationBasis: [{ required: true, message: '预计优化效益测算依据', trigger: 'blur' }]
      },
      isInit: true,
      cachePlanId: null
    }
  },

  async created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.id = this.$route.query.id
    this.isEdit = this.$route.query.isEdit
    // 顾超擅自修改
    if (this.isEdit == 1) {
      this.getOptimizationDetails()
    }
    this.getCurrentDate() // 获取当前日期
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('double-optimizing_project_approval')
    //优化类别
    this.getCategory()
  },

  computed: {
    rowSelection() {
      return {
        type: 'radio',
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange,
        getCheckboxProps: record => ({
          props: {
            // 禁止选中
            disabled: record.isProject == true ? true : false
          }
        })
      }
    },
    rowSelections() {
      return {
        selectedRowKeys: this.selectedRowKey,
        selectedRows: this.selectedRow, // 当前行所有数据
        onChange: this.onSelectChanges
      }
    }
  },
  watch: {
    // 'form.projectId':{
    //   handler(){
    //
    //   }
    // }
  },
  methods: {
    //获取优化类别
    getCategory(){
      this.loading.category = true
      list({type: 18}).then(res=>{
        this.loading.category = false
        this.optimizationCategoryList = res.data
      })
    },
    // 切换【所属单位】
    handleChange() {
      this.getPlanData()
    },
    selectOrg(val) {
      this.form.branchId = val[val.length - 2].orgId
    },
    getProjectInfo(info) {
      this.form._projectFormatName = info.projectFormatName?.join(',')
      this.form._designName = info.designName
      this.projectDeptId(info.projectDeptOrgId)
    },
    handlePageChange(pageNo, pageSize) {
      this.objFrom.pageNo = pageNo
      this.dataList()
    },
    showSizeChange(pageNo, pageSize) {
      this.objFrom.pageNo = 1
      this.objFrom.pageSize = pageSize
      this.dataList()
    },
    // 清空【双优化立项名称】联动的字段
    getPlanData() {
      this.form.optimizationName = ''
      this.form.typeId = undefined // 分类
      this.form.classification = undefined // 详细分类
      this.form._designStageName = null // 设计阶段（文本）
      this.form.designStageId = null // 设计阶段
      this.form._optimizeStageName = null // 优化类别（文本）
      this.form.optimizeStageId = null // 优化类别
      this.form.projectType = null // 工程类别（文本）
      this.form.projectTypeId = null // 工程类别
      this.form.part = null // 分部（文本）
      this.form.partId = null // 分部
      this.form.isNew = null // 创新
      this.form.proposerIds = [] //  提出人
      this.form.implementerIds = [] //  拟实施人
      this.form.forecastBenefit = null // 立项效益
      this.form.startTime = null // 计划实施时间
      this.form.majorCategory = null //  专业类别
      // this.dataList()
    },
    // 查询【选择】弹窗内的列表数据
    async dataList() {
      this.objFrom.query.status = 2
      this.objFrom.query.project = this.form.projectId
      return planListDetails(this.objFrom).then(res => {
        this.dataSource = res.data
        this.totalSize = res.totalSize
        this.totalPage = res.totalPage
      })
    },
    getContractStartDate(value) {
      var d1 = new Date(value)
      var year = d1.getFullYear() //年
      var month = d1.getMonth() + 1 //月
      var day = d1.getDate() //日

      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }

      this.startDate = year + '-' + month + '-' + day
      this.form.startTime = year + '-' + month + '-' + day

      if (this.form.endTime != '' || this.form.endTime != undefined) {
        this.endDate = this.form.endTime
      }

      if (this.endDate != '' && this.endDate != undefined) {
        let startTime = new Date(this.startDate)
        let endTime = new Date(this.endDate)

        if (startTime > endTime) {
          this.$message.error('计划实施时间不能大于计划结束时间！')
          this.form.startTime = undefined
          return
        }
      }
    },
    getContractEndDate(value) {
      var d1 = new Date(value)
      var year = d1.getFullYear() //年
      var month = d1.getMonth() + 1 //月
      var day = d1.getDate() //日

      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }

      this.endDate = year + '-' + month + '-' + day
      this.form.endTime = year + '-' + month + '-' + day

      if (this.form.startTime != '' || this.form.startTime != undefined) {
        this.startDate = this.form.startTime
      }

      if (this.startDate != '' && this.startDate != undefined) {
        var startTime = new Date(this.startDate)
        var endTime = new Date(this.endDate)

        if (endTime < startTime) {
          this.$message.error('计划结束时间不能小于计划实施时间！')
          this.form.endTime = undefined
          return
        }
      }
    },
    projectDeptId(val) {
      this.$nextTick(() => {
        this.deptId = val
        this.$refs.orgStaffAsync && this.$refs.orgStaffAsync.getOrgsTree()
        this.$refs.orgStaffAsync1 && this.$refs.orgStaffAsync1.getOrgsTree()
      })
    },
    /**
     * 这里需要选择项目部+设计管理中心的人员
     */
    async getDesignEmployee() {
      try {
        // 项目部+设计管理中心组织
        let p1 = null
        if (this.deptId) {
          // 项目部
          p1 = getProjectIdFromOrg({ pid: this.deptId, pageNum: 1, pageSize: 1000 })
        }
        // 设计中心
        const p2 = getProjectIdFromOrg({ code: 'designManage', pageNum: 1, pageSize: 1000 })
        const p3 = getProjectIdFromOrg({
          pid: 'ecf764c08dd94fa889ce31c380b1241c',
          code: 'BCDDM',
          pageNum: 1,
          pageSize: 1000
        })
        const p4 = getProjectIdFromOrg({
          pid: 'cdcfa929b51a47269f336364860c9f0c',
          code: 'BCDDM',
          pageNum: 1,
          pageSize: 1000
        })
        return Promise.all([p1, p2, p3, p4]).then(([res1, res2, res3, res4]) => {
          const list = (res1?.data?.list || [])
            .concat(res2?.data?.list || [])
            .concat(res3?.data?.list || [])
            .concat(res4?.data?.list || [])
          return {
            status: 200,
            data: list
          }
        })
      } catch (e) {
        return Promise.reject(e)
      }
    },
    getOptimitionDel() {
      this.form.planId = null
    },
    deleteExteriorFile() {
      let that = this
      if (that.file.dataAssement == null || that.selectedRowKey.length == 0) {
        that.$message.error('请先选中需要删除的附件！')
        return
      }
      if (that.id) {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            // 双优化立项
            // deleteOptimizationFile({businessId:that.id,applyFileIds:that.fileIds}).then(res=>{
            //     if(res.code == 200 || res.data.code == 200){
            //       that.$message.success("删除附件成功！")
            //       that.selectedRowKey = []
            //       that.getOptimizationDetails()
            //     }
            //   })

            let data = that.file.dataAssement
            let selectDatas = that.fileIds
            that.file.dataAssement = data.filter(item => {
              return !selectDatas.includes(item.commonId)
            })
            let commomIds = []
            that.file.dataAssement.forEach(function(obj, i) {
              commomIds.push(obj.commonId)
            })
            that.form.fileIds = commomIds
            that.selectedRowKey = []
            that.selectedRow = []
            that.$message.success('删除成功')
          },
          onCancel() {}
        })
      } else {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            deleteUploadFile({ fileIds: that.fileFileds }).then(res => {
              if (res.code == '0' || res.data.code == '0') {
                let data = that.file.dataAssement
                let selectDatas = that.fileIds
                that.file.dataAssement = data.filter(item => {
                  return !selectDatas.includes(item.commonId)
                })
                that.selectedRowKey = []
                that.$message.success('删除成功')
              }
            })
          },
          onCancel() {}
        })
      }
    },

    // onSelectChanges(selectedRowKeys, selectedRows) {
    //   this.selectedRowKey = selectedRowKeys
    //   this.selectedRow = selectedRows
    //   let fileFileds = []
    //   let fileIds = []
    //   selectedRows.forEach(function (obj, i) {
    //     fileFileds.push(obj.fileId) //
    //     fileIds.push(obj.commonId)
    //   })
    //   this.fileFileds = fileFileds.join(',') // 删除公共附件
    //   this.fileIds = fileIds // 有业务id 删除附件
    // },

    // beforeUpload(info) {
    //   this.uploadFile = info
    //   return false
    // },

    // handleChanges(info) {
    //   let that = this
    //   const data = new FormData()
    //   data.append('file', that.uploadFile)
    //   data.append('businessCode', that.file.businessCode)

    //   let arr = []
    //   uploadFile(data).then((res) => {
    //     if (res.code === 200) {
    //       arr.push(res.data)
    //       if (that.file.dataAssement != null) {
    //         that.file.dataAssement = arr.concat(that.file.dataAssement)
    //       } else {
    //         that.file.dataAssement = arr
    //       }

    //       let commomIds = []
    //       that.file.dataAssement.forEach(function (obj, i) {
    //         commomIds.push(obj.commonId)
    //       })
    //       that.form.fileIds = commomIds
    //       that.selectedRowKey = []
    //     }
    //   })
    // },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows[0]
    },

    handleSearch(val) {
      this.objFrom.query = val
      this.dataList()
    },

    // 根据【分类】查询【详细分类】
    getCategrys(val) {
      this.form.classification = null
      getTechnicalTypes({ type: 4, code: val, enabledCode: 1 }).then(res => {
        this.detailedClassification = res.data
      })
    },

    getReduceBenefit(val) {
      let that = this
      if (val != null && that.form.increaseBenefit != null) {
        that.form.forecastBenefit = parseFloat(parseFloat(that.form.increaseBenefit) + parseFloat(val)).toFixed(2)
      } else {
        if (that.form.reduceBenefit != null) {
          that.form.forecastBenefit = parseFloat(that.form.reduceBenefit).toFixed(2)
        } else {
          if (that.form.increaseBenefit != null) {
            that.form.forecastBenefit = parseFloat(that.form.increaseBenefit).toFixed(2)
          } else {
            that.form.forecastBenefit = 0
          }
        }
      }
    },
    getTotalBenefit(val) {
      let that = this
      if (val != null && that.form.reduceBenefit != null) {
        that.form.forecastBenefit = parseFloat(parseFloat(val) + parseFloat(that.form.reduceBenefit)).toFixed(2)
      } else {
        if (that.form.increaseBenefit != null) {
          that.form.forecastBenefit = parseFloat(that.form.increaseBenefit).toFixed(2)
        } else {
          if (that.form.reduceBenefit != null) {
            that.form.forecastBenefit = parseFloat(that.form.reduceBenefit).toFixed(2)
          } else {
            that.form.forecastBenefit = 0
          }
        }
      }
    },

    getCurrentDate() {
      var d1 = new Date()
      var year = d1.getFullYear() //年
      var month = d1.getMonth() + 1 //月
      var day = d1.getDate() //日

      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.form.createdTime = year + '-' + month + '-' + day
    },
    search() {
      this.$refs.table.refresh(true)
    },
    goBack() {
      this.$multiTab.close(this.$route.fullpath)
    },
    // 保存草稿
    saveDraft() {
      let that = this
      that.$refs.form1.validate( async (valid) => {
        // 验证通过
        if (valid) {
          if (that.loading.isDraft) return
          that.loading.isDraft = true
          // 保存产值信息草稿
          that.form.statusCode = 0
          // 已有草稿，再次保存草稿
          if (that.id) {
            // if (that.form.fileIdsInfo != null) {
            let arr = that.file.dataAssement
            let commonIds = []
            if (arr.length > 0) {
              arr.forEach(function(obj, i) {
                commonIds.push(obj.commonId)
              })
            }
            let newArr = [...new Set(commonIds)]
            that.form.fileIds = newArr
            // }

            // 需求要求保留两位小数，后台需要字符串
            that.form.forecastBenefit = that.form.forecastBenefit?.toFixed(2)
            if(this.form.planId != this.cachePlanId) {
              let q = {
                currentId: this.form.planId,
                originId: this.cachePlanId
              }
              try {
                await updateBasicStatusOptimization(q)
              } catch (e) {
                that.loading.isSubimt = false
              }
            }

            editOptimization(that.form)
              .then(res => {
                that.loading.isDraft = false
                if (res.data.code == 200) {
                  this.$refs.uploadTable.batchDeleteFile() // 删除文件
                  that.$message.success('保存草稿成功')
                  that.goBack()
                } else {
                  that.$message.error('保存草稿失败')
                }
              })
              .catch(() => {
                that.loading.isDraft = false
              })
          }
          // 新增草稿
          else {
            // 需求要求保留两位小数，后台需要字符串
            that.form.forecastBenefit = that.form.forecastBenefit?.toFixed(2)
            addOptimization(that.form)
              .then(res => {
                that.loading.isDraft = false
                if (res.code == 200) {
                  this.$refs.uploadTable.batchDeleteFile() // 删除文件
                  that.$message.success('保存草稿成功')
                  that.goBack()
                } else {
                  that.$message.error('保存草稿失败')
                }
              })
              .catch(() => {
                that.loading.isDraft = false
              })
          }
        }
        // 验证不通过
        else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
    },
    // 提交
    submit() {
      this.setProcessConfig = null
      let that = this
      that.$refs.form1.validate((valid, values) => {
        if (valid) {
          if (!this.file.dataAssement || this.file.dataAssement.length === 0) {
            this.$message.warning('请至少上传一个附件')
            return
          }
          if (that.loading.isSubimt) return
          that.loading.isSubimt = true
          // this.form.planId = this.form.planId || null
          // 编辑提交
          let arr = that.file.dataAssement
          let commonIds = []
          if (arr.length > 0) {
            arr.forEach(function(obj, i) {
              commonIds.push(obj.commonId)
            })
          }
          let newArr = [...new Set(commonIds)]
          that.form.fileIds = newArr
          if (that.id) {
            that.form.statusCode = 1
            // if (that.form.fileIdsInfo != null) {

            // }
            this.submitApprovalConfirm(this.processConfig, async (flag) => {
              if (!flag) {
                that.loading.isSubimt = false
                return
              }
              if(this.form.planId !== this.cachePlanId) {
                let q = {
                  currentId: this.form.planId,
                  originId: this.cachePlanId
                }
                try {
                  await updateBasicStatusOptimization(q)
                } catch (e) {
                  that.loading.isSubimt = false
                }
              }

              editOptimization(that.form)
                .then(res => {
                  that.loading.isSubimt = false
                  if (res.data?.code == 200 || res.code == 200) {
                    this.$refs.uploadTable.batchDeleteFile() // 删除文件
                    that.$message.success('提交成功')
                    this.businessId = res.data.id || that.id
                    this.setProcessConfig = this.processConfig
                  } else {
                    that.$message.error('提交失败')
                  }
                })
                .catch(() => {
                  that.loading.isSubimt = false
                })
            })
          }
          // 新增提交
          else {
            that.form.statusCode = 1
            this.submitApprovalConfirm(this.processConfig, flag => {
              if (!flag) {
                that.loading.isSubimt = false
                return
              }
              addOptimization(this.form)
                .then(res => {
                  that.loading.isSubimt = false
                  if (res.data?.code == 200 || res.code == 200) {
                    this.$refs.uploadTable.batchDeleteFile() // 删除文件
                    that.$message.success('提交成功')
                    this.businessId = res.data.id
                    this.setProcessConfig = this.processConfig
                  } else {
                    that.$message.error('提交失败')
                  }
                })
                .catch(() => {
                  that.loading.isSubimt = false
                })
            })
          }
        } else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
    },
    editorContent(val) {
      this.form.contentDels = val
    },
    getOptimizationDetails() {
      if (this.spinning) return
      this.spinning = true
      getOptimizationDetails({ id: this.id })
        .then(res => {
          this.isInit = false
          this.spinning = false
          if (res.code == 200 || res.data.code == 200) {
            // this.$nextTick(() => {
            //   this.form.projectId = res.data.projectId
            // })
            this.form = {
              ...res.data,
              _projectFormatName: null,
              _designName: null,
              forecastBenefit: res.data.forecastBenefit ? Number(res.data.forecastBenefit) : '',
              _designStageName: res.data.designStage,
              _optimizeStageName: res.data.optimizeStage
            }
            console.log(this.form, 'sds')
            this.view = this.form.typeId === '222' ||  this.form.typeId === 222//设计优化才能选择优化类别
            this.cachePlanId = this.form.planId
            this.forSelectPersonByProjectComp = {
              proposerId: res.data.proposerIds,
              implementId: res.data.implementerIds,
              proposer: res.data.proposer.replaceAll('/', ','),
              implement: res.data.implementer.replaceAll('/', ',')
            }
            //  组件内通过 created 调用方法，但此处需要主动调用一次，用于主动拼接展示列
            this.$refs['tcrRef'].getPersonList()
            this.$refs['nssrRef'].getPersonList()

            getTechnicalTypes({ type: 4, code: this.form.typeId, enabledCode: 1 }).then(res => {
              this.detailedClassification = res.data
            })

            this.file.dataAssement = res.data.fileIdsInfo || []
          }
        })
        .catch(() => {
          this.spinning = false
        })
    },
    // 点击【选择】
    changeData() {
      if (this.form.projectId == undefined || this.form.projectId == '') {
        this.$message.error('请先选择项目!')
        return
      }

      this.loading.isSelect = true
      //  查询【选择】弹窗内的列表数据
      this.dataList()
        .then(res => {
          this.visible = true
        })
        .finally(() => {
          this.loading.isSelect = false
        })
    },
    getUserBranch() {
      // 获取分公司
      getUserBranch().then(res => {
        this.companys = res.data
      })
    },
    getProjectById(value) {
      // 根据分公司查询项目
      getUserProject(value).then(res => {
        this.projectNames = res.data
      })
    },
    getPosts(value) {
      // 查询项目详情
      getProjectsDel(value).then(res => {
        this.projectType = res.type
      })
    },
    // 【选择双优化立项计划项】弹窗 - 确定选择
    handleOk() {
      console.log('selectedRows', this.selectedRows)
      this.form.planId = this.selectedRows.id
      this.getCategrys(this.selectedRows.category) // 查询【详细分类】的数据列表
      //暂时保留原有逻辑
      // this.form.optimizationNum = this.selectedRows.id
      this.form.optimizationName = this.selectedRows.name // 双优化立项名称
      this.form.typeId = this.selectedRows.category // 分类
      this.view = this.selectedRows.category === 222 || this.selectedRows.category === '222' //设计优化才能选择优化类别

      this.form.classification = this.selectedRows.detailedCategory // 详细分类
      this.form._designStageName = this.selectedRows.designStageName // 设计阶段（文本）
      this.form.designStageId = this.selectedRows.designStageId // 设计阶段
      this.form._optimizeStageName = this.selectedRows.optimizeStageName // 优化类别（文本）
      this.form.optimizeStageId = this.selectedRows.optimizeStageId // 优化类别
      this.form.projectType = this.selectedRows.projectType // 工程类别（文本）
      this.form.projectTypeId = this.selectedRows.projectTypeId // 工程类别
      this.form.part = this.selectedRows.part // 分部（文本）
      this.form.partId = this.selectedRows.partId // 分部
      this.form.isNew = this.selectedRows.isNew // 创新
      this.form.proposerIds = this.selectedRows.proposerId ? this.selectedRows.proposerId.split(',') : [] //  提出人
      this.form.implementerIds = this.selectedRows.implementId ? this.selectedRows.implementId.split(',') : [] //  拟实施人
      this.form.forecastBenefit = this.selectedRows.benefit // 立项效益
      this.form.startTime = this.selectedRows.startTime // 计划实施时间

      // 选中某一项时，professionalType 要做一次映射转换
      const majorCategoryMap = {
        CIVIL: 0,
        ELECTRICAL: 1,
        STRUCTURE: 2,
        LANDSCAPE: 3
      }
      this.form.majorCategory = majorCategoryMap[this.selectedRows.professionalType] // 专业类别
      /**
       * 【提出人】【拟实施人】使用了【双优化立项计划】内的组件，阅读代码后需要传入 :row
       * :row 用于拼接数组，进而回显列表
       */
      this.forSelectPersonByProjectComp = {
        proposerId: this.selectedRows.proposerId.split(','),
        implementId: this.selectedRows.implementId.split(','),
        proposer: this.selectedRows.proposer,
        implement: this.selectedRows.implement
      }
      //  组件内通过 created 调用方法，但此处需要主动调用一次，用于主动拼接展示列
      this.$refs['tcrRef'].getPersonList()
      this.$refs['nssrRef'].getPersonList()

      this.visible = false
    },

    handleCancel() {
      this.visible = false
    }
  }
}
</script>
